package com.jied.duodian.util.handler;

import com.jied.duodian.service.Impl.JwtUserDetailsServiceImpl;
import com.jied.duodian.util.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Description:
 *
 * @author LiJie
 * @date Created on 2020/10/30
 * WWW https://github.com/j6l
 */
@Component
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUserDetailsServiceImpl userDetailsService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain chain) throws ServletException, IOException {
        String token = request.getHeader( jwtTokenUtil.getHeader() );
        if (!StringUtils.isEmpty( token )) {
            String substring = token.substring( jwtTokenUtil.getTokenHead().length() );
            String username = jwtTokenUtil.getUsernameFromToken( substring );
            logger.info( "用户  " + username + "  经过认证过滤器 " );
            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                UserDetails userDetails = userDetailsService.loadUserByUsername( username );
                if (jwtTokenUtil.validateToken( substring, userDetails )) {
                    // 将用户信息存入 authentication，方便后续校验
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                            userDetails, null, userDetails.getAuthorities() );
                    authentication.setDetails( new WebAuthenticationDetailsSource().buildDetails( request ) );
                    // 将 authentication 存入 ThreadLocal，方便后续获取用户信息
                    SecurityContextHolder.getContext().setAuthentication( authentication );
                }
            }
            logger.info( "用户  " + username + "  认证成功去往下一步 " );
        }

        chain.doFilter( request, response );


    }

}
